import API from "@/api";

const state = {
	name: "",
	token: "",
	avatar: ""
};

const mutations = {
	SET_TOKEN: (state, token) => {
		state.token = token;
	},
	SET_NAME: (state, name) => {
		state.name = name;
	},
	SET_AVATAR: (state, avatar) => {
		state.avatar = avatar;
	},
	RESET_STATE: state => {
		(state.name = ""), (state.token = ""), (state.avatar = "");
	}
};

const actions = {
	// 登录并设置token
	login({ commit }, userInfo) {
		const { username, password } = userInfo;
		return new Promise((resolve, reject) => {
			API.login({ username: username.trim(), password: password })
				.then(response => {
					const { data } = response;
					commit("SET_TOKEN", data.token);
					resolve();
				})
				.catch(error => {
					reject(error);
				});
		});
	},

	// 获取用户信息并设置用户名头像
	getInfo({ commit, state }) {
		return new Promise((resolve, reject) => {
			API.getInfo(state.token)
				.then(response => {
					const { data } = response;
					if (!data) {
						return reject("获取用户信息失败，请重新登录");
					}
					const { name, avatar } = data;
					commit("SET_NAME", name);
					commit("SET_AVATAR", avatar);
					resolve(data);
				})
				.catch(error => {
					reject(error);
				});
		});
	},

	// 用户登出
	logout({ commit, dispatch, state }) {
		return new Promise((resolve, reject) => {
			API.logout(state.token)
				.then(() => {
					// 退出时清空token
					commit("RESET_STATE");
					// 同时清空缓存的tags
					dispatch("tagsView/delAllVisitedViews", {}, { root: true });
					resolve();
				})
				.catch(error => {
					reject(error);
				});
		});
	},

	// 移除
	resetToken({ commit }) {
		return new Promise(resolve => {
			commit("RESET_STATE");
			resolve();
		});
	}
};

export default {
	namespaced: true,
	state,
	mutations,
	actions
};
